const fs = require('fs')
const path = require('path')
const process = require('process')
const jsonic = require('jsonic')
const jsonfile = require('jsonfile')
const _ = require('lodash')
const logger = require('./logger')

/**
 * 创建act
 * @author tqboss
 * @module framework/common
 * @param {服务名称} serviceName
 * @param {act} pattern
 * @returns {返回包含指定服务的act}
 * @version 1.0.0
 */
exports.createServicePin = function (serviceName, pattern) {
  let obj = null
  if (_.isString(pattern)) {
    obj = jsonic(pattern)
  } else if (_.isObject(pattern)) {
    obj = pattern
  }
  if (obj === null) {
    logger.error(`服务${serviceName} 添加act ${pattern} 失败！`)
    process.exit()
  } else {
    _.unset(obj, 'service')
    return `service:${serviceName},${_.trim(jsonic.stringify(obj), '{}')}`
  }
}

/**
 * json对象转jsonic字符串
 * @author tqboss
 * @module framework/common
 * @param {json对象} obj
 * @returns {返回jsonic字符串}
 * @version 1.0.0
 */
exports.stringify = function (obj) {
  return _.trim(jsonic.stringify(obj), '{}')
}

/**
 * 读取服务配置内容，不存在时退出当前进程
 * @author tqboss
 * @module framework/common
 * @param {配置文件名} configName
 * @returns json格式配置
 * @version 1.0.0
 */
exports.assertAndGetAppConfig = function (configName) {
  if (process.argv.length < 1 || !fs.existsSync(process.argv[1])) {
    logger.error('启动参数错误!')
    process.exit()
  }

  const dirPath = path.dirname(process.argv[1])
  const configPath = path.join(dirPath, path.sep, configName)
  return jsonfile.readFileSync(configPath)
}

/**
 * 获取配置路径
 * @author tqboss
 * @module framework/common
 * @param {相对路径} configName
 * @returns 文件路径
 * @version 1.0.0
 */
exports.getAppConfigPath = function (configName) {
  if (process.argv.length > 1 && fs.existsSync(process.argv[1])) {
    const dirPath = path.dirname(process.argv[1])
    return path.join(dirPath, path.sep, configName)
  }
  return null
}
